<template>
  <div class="echarts_wrap" ref="echartsRef" :id="echarstId"></div>
</template>

<script setup>
import * as echarts from 'echarts';
import _ from 'lodash';
import { defaultConfig } from './config';
import { setUid } from '@/utils';
const props = defineProps({
  // echart的options
  chartConfig: {
    type: Object,
    default: () => {},
  },
  // 若不需要柱状图、这线图的默认配置，请传入false
  defaultConfig: {
    type: Boolean,
    default: true,
  },
});

const echarstId = setUid();
let echartsRef = ref();
let myChart = null;

const emits = defineEmits(['chartCanvas', 'chartDom']);

function init() {
  if (myChart) {
    myChart.dispose();
  }
  myChart = echarts.init(echartsRef.value);
  myChart.setOption(config.value);
  observerEl();
}

const resizeHandler = _.debounce(() => {
  emits('chartCanvas', myChart);
  emits('chartDom', echartsRef.value);
  myChart.resize();
}, 100);

function observerEl() {
  const resizeObserver = new ResizeObserver(entries => {
    resizeHandler();
  });
  resizeObserver.observe(echartsRef.value);
}

const config = computed(() => {
  return props.defaultConfig ? _.merge({}, defaultConfig, props.chartConfig) : props.chartConfig;
});

watch(
  () => props.chartConfig,
  newOptions => init(newOptions),
  { deep: true }
);
</script>

<style scoped>
.echarts_wrap {
  width: 100%;
  height: 100%;
}
</style>
